define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            Fast.config.openArea = ['95%','95%'];
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'course/order/index' + location.search,
                    add_url: 'course/order/add',
                    edit_url: 'course/order/edit',
                    del_url: 'course/order/del',
                    multi_url: 'course/order/multi',
                    import_url: 'course/order/import',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                showExport: false,
                fixedColumns: true,
                fixedRightNumber: 1,
                exportTypes: ['excel'],
                exportOptions: {
                    fileName: '订单导出_' + Moment().format("YYYY-MM-DD"),
                    preventInjection: false,
                    mso: {
                        onMsoNumberFormat: function (cell, row, col) {
                            return !isNaN($(cell).text()) ? '\\@' : '';
                        },
                    },
                    ignoreColumn: [0, 'operate'] //默认不导出第一列(checkbox)与操作(operate)列
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'school_id', title: __('School'), searchList: Config.schoolGroup, formatter: Table.api.formatter.label},

                        // {field: 'user.nickname', title: __('User.nickname'), operate: 'LIKE'},
                        {field: 'parent_name', title: __('ParentName'), operate: 'LIKE'},
                        {field: 'student_name', title: __('StudentName'), operate: 'LIKE'},
                        {field: 'order_sn', title: __('Order_sn'), operate: 'LIKE'},
                        {field: 'order_goods', title: __('班次'), operate: false, formatter: Controller.api.formatter.order_goods},
                        {field: 'type', title: __('Type'), searchList:Config.typeList,  formatter: Table.api.formatter.label},
                        {field: 'status', title: __('Status'), searchList:Config.statusList,  formatter: Table.api.formatter.label},
                        // {field: 'status_text', title: __('Status'), operate: false, formatter: Table.api.formatter.label, custom:{"退款":"danger","取消":"danger","已取消":"danger", "待支付":"info","待发货":"warning", "已发货":"success", "已收货":"success","待评价":"info", "已完成":"success"}},
                        {field: 'money', title: __('Money'), operate: false, formatter: Controller.api.formatter.order_money},
                        // {field: 'course_price', title: __('Course_price'), operate:'BETWEEN'},
                        {field: 'pay_time', title: __('Pay_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [

                                {
                                    name: 'edit',
                                    text: __('Detail'),
                                    title: __('Detail'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'course/order/edit',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },

                                {
                                    name: 'cancel_order',
                                    text:'取消订单',
                                    title:function(row){
                                        return row.order_sn + __("Cancelled");
                                    },
                                    confirm:"确定取消订单吗?",
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    url: 'course/order/cancel_order',
                                    visible: function (row) {
                                        if( row.status == 10){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    refresh:true
                                },
                                {
                                    name: 'refund_order',
                                    // text:"退款",
                                    text:function(row){
                                        if(row.type == 3){
                                            return "取消";
                                        } else {
                                            return "退款";
                                        }
                                    },
                                    title:function(row){
                                        if(row.type == 3){
                                            return row.order_sn + "取消";
                                        } else {
                                            return row.order_sn + "退款";
                                        }
                                    },

                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'course/order/refund_order',
                                    extend: 'data-area=\'["50%","50%"]\'',
                                    // click:function(index,row){
                                    //     var msg = '';
                                    //     if(row.type == 3){
                                    //         msg = "请填写取消原因";
                                    //     } else {
                                    //         msg = "请填写退款原因";
                                    //     }
                                    //     layer.prompt({title: msg, formType: 2}, function(text, index){
                                    //         Fast.api.ajax('course/order/refund_order?ids='+row.id+'&refund_content='+text,function (data,ret) {
                                    //             layer.close(index);
                                    //             table.bootstrapTable('refresh', {});
                                    //         });
                                    //     });
                                    //
                                    // },
                                    visible: function (row) {
                                        if(row.status == 20 && (row.type <=2 )){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    refresh:true
                                },
                                {
                                    name: 'stop_order',
                                    text: __('停课'),
                                    title: __('停课'),
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    // url: 'course/order/refund_order',
                                    click:function(index,row){
                                        var msg = '请填写停课原因';

                                        layer.prompt({title: msg, formType: 2}, function(text, index){
                                            Fast.api.ajax('course/order/stop_order?ids='+row.id+'&stop_content='+text,function (data,ret) {
                                                layer.close(index);
                                                table.bootstrapTable('refresh', {});
                                            });
                                        });

                                    },
                                    visible: function (row) {
                                        if( row.status == 20){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    refresh:true
                                },
                                {
                                    name: 'restore_order',
                                    text: __('恢复上课'),
                                    title: __('恢复上课'),
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    confirm:"确定要恢复上课吗?",
                                    url: 'course/order/restore_order',
                                    visible: function (row) {
                                        if( row.status == -2){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    refresh:true
                                },
                                {
                                    name: 'change_money',
                                    text: __('修改价格'),
                                    title:function(row){
                                        return row.order_sn + __("修改价格");
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    url: 'course/order/change_money',
                                    visible: function (row) {
                                        if(row.status >= 20 && row.type == 3){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    extend:'data-area=["30%","50%"]',
                                    refresh:true
                                },
                                {
                                    name: 'use_hour',
                                    // text:"退款",
                                    text:"消耗课时",
                                    title:"消耗课时",

                                    classname: 'btn btn-xs btn-warning btn-click',
                                    // url: 'course/order/refund_order',
                                    click:function(index,row){
                                        var msg = '请填写消耗课时数';
                                        layer.prompt({title: msg, formType: 2,area:["100%","35px"]}, function(text, index){
                                            Fast.api.ajax('course/order/use_hour?ids='+row.id+'&hour='+text,function (data,ret) {
                                                layer.close(index);
                                                table.bootstrapTable('refresh', {});
                                            });
                                        });

                                    },
                                    visible: function (row) {
                                        if(row.status == 20 && row.surplus_class_hour >0){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    refresh:true
                                },
                                {
                                    name: 'order_sign',
                                    // text:"退款",
                                    text:"课时日志",
                                    title:"课时日志",

                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: function (row){
                                        return 'course/order_sign/index?order_id='+row.id;
                                    },

                                },
                                {
                                    name: 'del',
                                    // text:"退款",
                                    text:"删除",
                                    title:"删除",
                                    confirm:"确定要删除当前订单吗？",
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    visible: function (row) {
                                        if(row.type == 3){
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    url: "course/order/del",
                                    refresh:true
                                },
                            ],
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        restore_order: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {

            Controller.api.bindevent();

        },
        deliver_order: function () {
            Controller.api.bindevent();
        },
        refund_order: function () {
            Controller.api.bindevent();
        },
        change_money: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {

                $("img").click(function () {
                    var src = $(this).attr("src");
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        shadeClose: true,
                        skin: 'img_box',
                        content: '<img style="display: block;margin: 0 auto;width: 100%" src="'+$(this).attr("src")+'">'
                    });
                });
                // //用户选择参数绑定
                // $("#c-user_id").data("params", function (obj) {
                //     console.log("用户选择参数绑定")
                //     //obj为SelectPage对象
                //     var user_id = $("#c-user_id").val();
                //     if(user_id > 0){
                //         return {custom: {id: $("#c-user_id").val()}};
                //     }
                //
                // });
                //学员选选中后操作
                $(document).on("change", "#c-user_id", function(obj,row){
                //用户选中后操作
                    var user_id = $("#c-user_id").val();
                    // if(user_id)
                    console.log("用户选中后操作"+user_id)
                    //后续操作
                    $('#c-student_id').selectPageClear();
                });

                //学员选择参数绑定
                $("#c-student_id").data("params", function (obj) {
                    // console.log("学员选择参数绑定")
                    //obj为SelectPage对象
                    var user_id = $("#c-user_id").val();
                    if(user_id > 0){
                        return {custom: {user_id: $("#c-user_id").val()}};
                    }

                });
                //学员选选中后操作
                $(document).on("change", "#c-student_id", function(obj,row){
                    // console.log("学员选选中后操作");
                    //后续操作
                    var student_id = $("#c-student_id").val();
                    // console.log("学员选中id"+student_id)
                    if(student_id > 0){

                        console.log("当前学员id"+student_id);
                        Fast.api.ajax({
                            url:"user/student/getUserId",
                            data: {
                                student_id: student_id,

                            }
                        },function (data){
                            var user_id = $("#c-user_id").val();


                            if(user_id != data){
                                $('#c-user_id').val(data);
                                $('#c-user_id').selectPageRefresh();
                            }
                            return false;

                        });
                    }

                });

                $(document).on('click', "[data-toggle='select_student']", function () {
                    var that = this;
                    var user_id = $("#c-user_id").val();

                    if(!user_id){
                        layer.msg("请选择用户创建");
                        return;
                    }
                    var url = "user/student/add?user_id="+user_id;

                    Fast.api.open(url, '添加学员', {
                        callback: function (res) {
                            console.log(res);
                        }
                    });
                });

                $(document).on('click', "[data-toggle='select_classes']", function () {
                    var that = this;
                    var data_id = $("#c-data_id").val();
                    if(data_id <=0){
                        layer.msg("请选择课程后操作");
                        return;
                    }
                    var url = "course/course/select_classes?course_id="+data_id;

                    Fast.api.open(url, '选择班次', {
                        callback: function (res) {
                            $(".classes_div").html("");
                            $.each(res,function(index,items){

                                $(".classes_div").append("<div><span>校区："+items.school_name+"</span>  " +
                                    "<span>班次："+items.classes_name+"</span>  " +
                                    "<span>时间："+items.time_text+"</span></div>");
                            });
                            $(".config").val(JSON.stringify(res));
                            console.log(res);
                        }
                    });
                });
                Form.api.bindevent($("form[role=form]"));

            },
            formatter: {//渲染的方法
                order_goods: function (value, row, index) {
                    var orderGoods = row.order_goods;
                    var html = "";
                    if(orderGoods){
                        orderGoods.forEach(function (element) {
                            // html+="<div  class='goodsBox'>"
                            html += "<div class='panel panel-default'>\n" +
                                "  <ul class='list-group '>\n" +
                                "    <li class='list-group-item'>课程:"+element.course_name+"</li>\n" +
                                "    <li class='list-group-item'>班次:"+element.classes_name+"</li>\n" +
                                "    <li class='list-group-item'>时间:<span class='sku_name'>"+element.time_name+"</span></li>\n" +
                                "    <li class='list-group-item'>老师:<span class='sku_name'>"+(element.teacher.nickname?element.teacher.nickname:'无')+"</span></li>\n" +
                                "  </ul>\n" +
                                "</div>" ;
                            // html+="</div>"
                            // html+=element.goods_name
                        });
                    }

                    return html;
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    // return '<a class="btn-change text-success" data-url="example/bootstraptable/change" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.title == '' ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                order_money: function (value, row, index) {
                    var html =  "总金额："+row.money +"<br/>" +
                        "课程价格：" + row.course_price+"<br/>" +
                        "优惠金额：" + row.discount_money+"<br/>" +
                        "VIP优惠金额：" + row.vip_discount_money+"<br/>" +
                        "总课时：" + row.class_hour+"<br/>" +
                        "剩余课时：" + row.surplus_class_hour+"<br/>";
                    return html;
                },
            },
        }
    };
    return Controller;
});